package com.molange.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.molange.behavior.mapper.LikeBehaviorMapper;
import com.molange.behavior.service.FavouriteService;
import com.molange.behavior.utils.BehaviorThreadLocalUtil;
import com.molange.feign.client.PublishClient;
import com.molange.feign.client.UserClient;
import com.molange.model.behavior.pojos.LikeBehavior;
import com.molange.model.common.FeedResponseResult;
import com.molange.model.common.ResponseResult;
import com.molange.model.feed.Video;
import com.molange.model.publish.pojos.Publish;
import com.molange.model.publish.pojos.PublishInformation;
import com.molange.model.user.pojos.AppUser;
import com.molange.model.user.vo.Author;
import com.molange.model.user.vo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author wangshiqi
 * @version 1.0
 * @date 2023/1/30 21:41
 */
@Service
@Slf4j
public class FavouriteServiceImpl extends ServiceImpl<LikeBehaviorMapper, LikeBehavior> implements FavouriteService {

    @Autowired
    private UserClient userClient;
    @Autowired
    private PublishClient publishClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户点赞服务
     *
     * @param token
     * @param videoId
     * @param actionType
     * @return
     */
    @Override
    @Transactional
    public ResponseResult likeBehavior(String token, String videoId, String actionType) {

        log.info("检测到用户登录请求");
        //判断用点击状态
        if (StringUtils.isBlank(actionType) || StringUtils.isBlank(videoId)) {
            return ResponseResult.errorResult(100, "非法的用户请求");
        }
        AppUser user = BehaviorThreadLocalUtil.getUser();
        //使用Redis判断
        String stringKey = "LIKE" + user.getId();//设置点赞数据
        LambdaQueryWrapper<LikeBehavior> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(LikeBehavior::getPublishId, videoId);
        queryWrapper.eq(LikeBehavior::getUserId, user.getId());
        LikeBehavior one = getOne(queryWrapper);
        if (null != one && "1".equals(videoId)) {
            return ResponseResult.errorResult(100, "非法的用户请求");
        }
        LikeBehavior likeBehavior = new LikeBehavior();
        likeBehavior.setPublishId(Integer.parseInt(videoId));
        likeBehavior.setUserId(user.getId());
        //1-点赞 2-取消
        log.info("开始进行操作");
        if ("1".equals(actionType) || null == one) {//数据库没有点赞信息
            save(likeBehavior);
            //保存完成，需要更新视频的数据
            rabbitTemplate.convertAndSend("tiktok.topic", "behavior.like", Integer.parseInt(videoId));
            return new ResponseResult(0, "点赞完成");
        }
        if ("2".equals(actionType) && null != one) {//有点赞数据需要取消
            //取消赞
            rabbitTemplate.convertAndSend("tiktok.topic", "behavior.unlike", Integer.parseInt(videoId));
            removeById(one.getId());
            return new ResponseResult(0, "取消成功");
        }
        return ResponseResult.errorResult(100, "非法的用户请求");
    }

    /**
     * 获取喜欢列表
     *
     * @param userId
     * @param token
     * @return
     */
    @Override
    public FeedResponseResult getLikeList(String userId, String token) {
        log.info("开始进行用户喜欢列表获取");
        LambdaQueryWrapper<LikeBehavior> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(LikeBehavior::getUserId, userId);
        //返回query的了list对象
        List<LikeBehavior> queryList = list(queryWrapper);
        //遍历获取publish的id
        List<Publish> publishesList = new ArrayList();
        for (LikeBehavior likeBehavior : queryList) {
            Publish publishes = publishClient.gtePublishData(likeBehavior.getPublishId());
            publishesList.add(publishes);//获取所有视频信息
        }
        //获取视频数据
        log.info("视频列表获取完成");
        //获取视频点赞数据
        List<Video> video_list = new ArrayList<>();
        for (Publish publish : publishesList) {
            Author author = new Author();
            Video video = new Video();
            video.setId(publish.getId());
            video.setIs_favorite(false);
            video.setTitle(publish.getTitle());
            video.setPlay_url(publish.getUrl());
            video.setCover_url(publish.getPictureUrl());
            log.info("开始获取点赞信息");
            PublishInformation publishInformation1 = publishClient.getPublishInformation(publish.getId());
            video.setComment_count(publishInformation1.getComment());//视频点赞数
            video.setFavorite_count(publishInformation1.getLikes());//视频评论数
            User userData = userClient.userMessageByFeign(publish.getUserId().toString(), token);
            author.setIs_follow(userData.is_follow());
            author.setFollow_count(userData.getFollow_count());
            author.setId(userData.getId());
            author.setName(userData.getName());
            author.setFollower_count(userData.getFollower_count());
            video.setAuthor(author);
            video_list.add(video);
        }

        return new FeedResponseResult(0, "成功", video_list, 0);
    }

    /**
     * 获取其是否是喜欢列表
     * @param userId
     * @param publishId
     * @return
     */
    @Override
    public Boolean getIslikeBehavior(Integer userId, Integer publishId) {
        LambdaQueryWrapper<LikeBehavior> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(LikeBehavior::getUserId, userId);//对比用户id
        queryWrapper.eq(LikeBehavior::getPublishId, publishId);//对比视频id
        LikeBehavior one = getOne(queryWrapper);
        if (one == null) {
            //没有获取到信息
            return false;
        }
        return true;
    }

    /**
     * 获取喜欢列表
     * @param userId
     * @param token
     * @return
     */
    @Override
    public FeedResponseResult getLikeList(String userId, String token) {
        log.info("开始进行用户喜欢列表获取");
        LambdaQueryWrapper<LikeBehavior> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(LikeBehavior::getUserId,userId);
        //返回query的了list对象
        List<LikeBehavior> queryList = list(queryWrapper);
        //遍历获取publish的id
        List<Integer> publishListId=new ArrayList();
        for (LikeBehavior likeBehavior : queryList) {
            publishListId.add(likeBehavior.getPublishId());
        }
        //获取视频数据
        List<Publish> publishesList = publishClient.gtePublishDataList(publishListId);
        log.info("视频列表获取完成");
        //获取视频点赞数据
        List<Video> video_list = new ArrayList<>();
        List<PublishInformation> publishInformation = publishClient.getPublishInformation(publishListId);
        for (Publish publish : publishesList) {
            Author author = new Author();
            Video video = new Video();
            video.setId(publish.getId());
            video.setIs_favorite(true);
            video.setTitle(publish.getTitle());
            video.setPlay_url(publish.getUrl());
            video.setCover_url(publish.getPictureUrl());
            log.info("开始获取点赞信息");
            List<Integer>list =new ArrayList<>();
            list.add(publish.getId());
            List<PublishInformation> publishInformation1 = publishClient.getPublishInformation(list);
            PublishInformation information = publishInformation1.get(0);
            video.setComment_count(information.getComment());//视频点赞数
            video.setFavorite_count(information.getLikes());//视频评论数
            User userData = userClient.userMessageByFeign(publish.getUserId().toString(), token);
            author.setIs_follow(userData.is_follow());
            author.setFollow_count(userData.getFollow_count());
            author.setId(userData.getId());
            author.setName(userData.getName());
            author.setFollower_count(userData.getFollower_count());
            video.setAuthor(author);
            video_list.add(video);
        }

        return new FeedResponseResult(0,"成功",video_list,0);
    }
}
